package org.yylnb.openplatform.search.config;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author RainLin
 * @date 2020/8/1 - 11:13
 */
@Configuration
public class SearchConfig {

    @Bean // 相当于<bean class ="org.elasticsearch.client.RestHighLevelClient" id ="restHighLevelClient">
    public RestHighLevelClient restHighLevelClient() {

        HttpHost httpHost = new HttpHost("10.0.134.208", 9200);
        RestClientBuilder builder = RestClient.builder(httpHost);
        //额外的配置,凡是配置链接服务器之类的对象,基本上都要配置超时时间
        setConnectTimeOut(builder);
        setConnectionConfig(builder);
        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(builder);
        return restHighLevelClient;
    }

    /**
     * 设置和连接数相关的
     * @param builder
     */
    private void setConnectionConfig(RestClientBuilder builder) {
        builder.setHttpClientConfigCallback(builder1->{

            builder1.setMaxConnTotal(100);//链接的总数量
            builder1.setMaxConnPerRoute(100);//每个路由能链接的数量

            return builder1;
        });
    }

    private void setConnectTimeOut(RestClientBuilder builder) {
        builder.setRequestConfigCallback((builder1)->{

            builder1.setConnectTimeout(5000);
            builder1.setSocketTimeout(5000);
            builder1.setConnectionRequestTimeout(5000);

            return builder1;
        });
    }
}
